import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import prisma from '@/lib/prisma'

export async function GET(req: NextRequest) {
    try {
        const session = await getServerSession(authOptions)

        if (!session?.user) {
            return NextResponse.json({ error: '未登录' }, { status: 401 })
        }

        console.log(`获取实验列表，用户: ${session.user.email}，角色: ${session.user.role}`)

        const studentExperiments = await prisma.experiment.findMany({
            where: {
                // 学生只能看到自己被授权的实验
                authorizedExperiments: {
                    some: {
                        studentId: session.user.id,
                    },
                },
            },
            include: {
                groups: {
                    where: {
                        members: {
                            some: {
                                userId: session.user.id,
                            },
                        },
                    },
                    include: {
                        members: {
                            include: {
                                user: {
                                    select: {
                                        id: true,
                                        name: true,
                                        email: true,
                                    },
                                },
                            },
                        },
                    },
                },
            },
            orderBy: {
                createdAt: 'desc',
            },
        });

        return NextResponse.json(studentExperiments)
    } catch (error) {
        console.error('获取实验列表失败:', error)
        return NextResponse.json(
            { error: '获取实验列表失败' },
            { status: 500 }
        )
    }
}